package com.wenjh.jdmzt.android.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

/**
 * 广播。<br/>
 * 使用方式示例:<br/>
 * <pre>
 * BaseReceiver receiver = new BaseReceiver();
 * receiver.register("com.immomo.momo.action.message");
 * receiver.setReceiveListener(listener);
 * ...
 * unregisterReceiver(receiver);
 * 
 * 或者推荐的方式为，为每一种广播实现一个派生类，例如
 * public class MessageReceiver extends BaseReceiver{
 * 		MessageReceiver(Context context) {
 *      	super(context, "com.immomo.momo.action.message");
 *      }
 * }
 * 
 * 然后在程序中这样使用：
 * BaseReceiver receiver = new MessageReceiver();
 * receiver.serReceiverListener(listener);
 * ...
 * unregisterReceiver(receiver);
 * </pre>
 * 
 * @author <a href="mailt:wenlin56@sina.com"> wjh </a>
 */
public class BaseReceiver extends BroadcastReceiver {
	private Context context = null;
	private IBroadcastReceiveListener receiveListener = new IBroadcastReceiveListener() {
		@Override
		public void onReceive(Intent intent) {
			
		}
	};
	
	public BaseReceiver() {
	}
	
	public BaseReceiver(Context context, String action) {
		this.context = context;
		register(action);
	}
	
	public BaseReceiver(Context context, IntentFilter filter) {
		this.context = context;
		register(filter);
	}
	
	public BaseReceiver(Context context) {
		this.context = context;
	}
	
	@Override
	public final void onReceive(Context context, Intent intent) {
		receiveListener.onReceive(intent);
		doReceive(context, intent);
		
	}
	
	public void doReceive(Context context, Intent intent){
		
	}
	
	public void register(String... action) {
		IntentFilter filter = new IntentFilter();
		for (String string : action) {
			filter.addAction(string);
		}
		register(filter);
	}
	
	public void register(IntentFilter filter) {
		context.registerReceiver(this, filter);
	}

	public void setReceiveListener(IBroadcastReceiveListener receiveListener) {
		this.receiveListener = receiveListener;
	}
	
	
	public interface IBroadcastReceiveListener {
		void onReceive(Intent intent);
	}
	
}
